function alert(txt) {
    $.messager.alert('提示信息', txt)
}

$.extend($.fn.validatebox.defaults.rules, {
    INT: {
        validator: function (value) {
            if (/^[+]?[0-9]+\d*$/i.test(value)) {

                if ($(this).attr('placeholder') != '' && $(this).attr('placeholder') != null) {
                    if (value <= parseInt($(this).attr('placeholder'))) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }
            } else {
                return false;
            }
        },
        message: '必须是整数/不能超过输入框提示数量'
    },
    RANGE: {
        validator: function (value, param) {
            if (value > param[0] && value <= param[1]) {
                return true
            } else {
                return false
            }
        },
        message: '输入的数字在{0}到{1}之间'
    },
    FL: {
        validator: function (value) {
            return /^[1-9]\d*(\.\d+)?$/.test(value);
        },
        message: '输入数字格式不正确'
    },
    YZ: {
        validator: function (value) {
            if (!/^[+]?[0-9]+\d*$/i.test(value)) {
                return false;
            }
            value = value - 0;
            var sum = ($("#sp table td").length / $("#sp table tr").length - 1) - 1
            if (value % sum == 0) {
                return true;
            } else {
                return false;
            }
        },
        message: '请输入尺码数量的倍数'
    },
    INTE: {
        validator: function (value) {
            if (/^[+]?[0-9]+\d*$/i.test(value)){
                if (parseInt($('#bjdg').datagrid("getSelected").yanzheng) >= value) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        },
        message: "必须是整数或已超出实际数量"
    }
});

//全局参数
var kehu;
var product;
var danjuId;
var chukudan;
var chukuleixing;
var state = -1;
var stateB = -1;
var stateC = -1;
var stateD = -1;


/**
 * 选择状态
 */
function zhuangtai() {
    $('#dg').datagrid("hideColumn","zhidanrenName")
    $('#dg').datagrid("hideColumn","zhidanshijian")
    $('#dg').datagrid("hideColumn","bohuirenName")
    $('#dg').datagrid("hideColumn","bohuishijian")
    $('#dg').datagrid("hideColumn","shenherenName")
    $('#dg').datagrid("hideColumn","shenheshijian")
    $('#dg').datagrid("hideColumn","tongguorenName")
    $('#dg').datagrid("hideColumn","tongguoshijian")
    $('#dg').datagrid("hideColumn","chukurenName")
    $('#dg').datagrid("hideColumn","chukushijian")
    $('#dg').datagrid("hideColumn","beizhu")
    $('#dg').datagrid("hideColumn","note")
    if ($('#zt1').prop('checked')) {
        state = 0;
        $('#dg').datagrid("showColumn","zhidanrenName")
        $('#dg').datagrid("showColumn","zhidanshijian")
        $('#dg').datagrid("showColumn","bohuirenName")
        $('#dg').datagrid("showColumn","bohuishijian")
        $('#dg').datagrid("showColumn","beizhu")
    } else {
        state = -1;
    }
    if ($('#zt2').prop('checked')) {
        stateB = 1;
        $('#dg').datagrid("showColumn","zhidanrenName")
        $('#dg').datagrid("showColumn","zhidanshijian")
        $('#dg').datagrid("showColumn","bohuirenName")
        $('#dg').datagrid("showColumn","bohuishijian")
        $('#dg').datagrid("showColumn","beizhu")
        $('#dg').datagrid("showColumn","shenherenName")
        $('#dg').datagrid("showColumn","shenheshijian")

    } else {
        stateB = -1;
    }
    if ($('#zt3').prop('checked')) {
        stateC = 2;
        $('#dg').datagrid("showColumn","zhidanrenName")
        $('#dg').datagrid("showColumn","zhidanshijian")
        $('#dg').datagrid("showColumn","bohuirenName")
        $('#dg').datagrid("showColumn","bohuishijian")
        $('#dg').datagrid("showColumn","beizhu")
        $('#dg').datagrid("showColumn","shenherenName")
        $('#dg').datagrid("showColumn","shenheshijian")
        $('#dg').datagrid("showColumn","tongguorenName")
        $('#dg').datagrid("showColumn","tongguoshijian")
        $('#dg').datagrid("showColumn","note")
    } else {
        stateC = -1;
    }
    if ($('#zt4').prop('checked')) {
        stateD = 3;
        $('#dg').datagrid("showColumn","zhidanrenName")
        $('#dg').datagrid("showColumn","zhidanshijian")
        $('#dg').datagrid("showColumn","bohuirenName")
        $('#dg').datagrid("showColumn","bohuishijian")
        $('#dg').datagrid("showColumn","beizhu")
        $('#dg').datagrid("showColumn","shenherenName")
        $('#dg').datagrid("showColumn","shenheshijian")
        $('#dg').datagrid("showColumn","tongguorenName")
        $('#dg').datagrid("showColumn","tongguoshijian")
        $('#dg').datagrid("showColumn","note")
        $('#dg').datagrid("showColumn","chukurenName")
        $('#dg').datagrid("showColumn","chukushijian")
    } else {
        stateD = -1;
    }

}

//获得出库列表
function getChuKuList() {
    zhuangtai()
    var etime = $("#etime").val();
    if (null != etime && '' != etime) {
        etime += " 23:59:59";
    }
    $("#dg").datagrid({
        url: path + '/chuku/chukulist.do',
        queryParams: {
            jgId: $('#bumeng').combotree("getValue"),
            fenlei: 1,//0是出库1是出库退货
            chukuleixing: -1,
            state: state,
            stateB: stateB,
            stateC: stateC,
            stateD: stateD,
            qtime: $('#qtime').val(),
            etime: etime,
            wldwName: $('#key').val()

        }
    });
}



/***
 *重置搜索条件
 */

function chongzhi() {
    $('#qtime').combo('setValue', '');
    $('#etime').combo('setValue', '');
    $("#key").searchbox('setValue', '');
    getChuKuList()
}

//加载子表
function loadChildren(val) {
    var row = $('#dg').datagrid('getSelected');
    $("#subDatagrid").datagrid({
        url: path + '/chuku/chukusonlist.do',
        queryParams: {
            chukuId: row.id,
            type: val
        }
    });

}


$(function () {
    $('#bumeng').combotree({
        url: path + '/jg/tree.do',
        required: true,
        loadFilter: function (data) {
            return data.rows
        }, onLoadSuccess: function (node, data) {
            if (data.length > 0) {
                $("#bumeng").combotree('setValue', data[0].id);
                getChuKuList()
            }
        }, onClick: function () {
            getChuKuList()
        }
    })

    $('#yearandseason').combobox({
        url: path + "/chuku/findYearAndSeason.do",
        valueField: 'yearandseason',
        textField: 'yearandseason',
        loadFilter: function (data) {

            return data.data
        }
    })


})

/***
 * 开启编辑框
 */
function winOpen() {
    //加载退货人员
    $('#kehu').combobox({
        url: path + '/pifashang/pfslistth.do',
        valueField: 'id',
        textField: 'kehuming',
        onLoadSuccess: function () {  // 加载完成后,设置选中第一项
            var val = $(this).combobox("getData");
            for (var item in val[0]) {
                if (item == "id") {
                    $(this).combobox("select", val[0][item]);
                }
            }
        },
        onSelect: function (record) {
            $("#SHDZ").val(record.address)
            $('#phone').val(record.phone)
            kehu = record  //选者客户赋予全局变量
            $('#sp').empty();
            $('#se').combobox("clear")
            $('#chukudan').combogrid("clear")
        }, loadFilter: function (data) {
            return data.data
        },onHidePanel:function(){
            $("#se").combobox({
                url: path + '/production/findAllProForkehuid.do?kehuId=' + kehu.id,
                valueField: 'id',
                textField: 'product',
                onSelect: function (record) {
                    product = record//选者款号赋予全局变量
                    $('#sp').empty();
                    $('#chukudan').combogrid("clear")
                },
                loadFilter: function (data) {
                    return data.data
                }, onHidePanel: function () {
                    $("#chukudan").combogrid({
                        panelWidth: 550,
                        width: 120,
                        fitColumns: true,
                        height: 25,
                        idField: 'id',
                        textField: 'chukudanhao',
                        mode: 'remote',
                        url: path + '/chuku/chukudan.do?kehuId=' + kehu.id + "&productId=" + product.id,
                        columns: [[
                            {field: 'id', title: '入库Id', hidden: 'true'},
                            {field: 'chukudanhao', title: '出库单号', align: 'center'},
                            {
                                field: 'chukuleixing', title: '出库类型', align: 'center',
                                formatter: function (value, row, index) {
                                    if (value == 0) {
                                        return "批发"
                                    } else if (value == 1) {
                                        return "分销"
                                    } else {
                                        return "其他"
                                    }
                                }
                            },
                            {
                                field: 'state', title: '状态', align: 'center',
                                formatter: function (value, row, index) {
                                    if (value == 3) {
                                        return "已出库"
                                    } else {
                                        return "其他"
                                    }
                                }
                            },
                            {field: 'wldwName', title: '往来单位', align: 'center'},
                            {field: 'phone', title: '联系方式', align: 'center'},
                            {field: 'address', title: '地址', align: 'center'},
                            {field: 'zshuliang', title: '数该款量', align: 'right'},
                            /* {field: 'zongjia', title: '总价', align: 'right'},*/
                            {field: 'address', title: '地址', align: 'center'},
                            {field: 'chukushijian', title: '出库时间', align: 'center'},
                            {field: 'danjia', title: 'danjia', align: 'center'}
                        ]],
                        loadFilter: function (data) {
                            return data.data
                        },
                        onLoadSuccess: function () {  // 加载完成后,设置选中第一项
                            $('#chukudan').next('span').find('input').focus()
                            $('#chukudan').combo('showPanel')
                        },
                        onSelect: function (rowIndex, rowData) {
                            danjuId = rowData.id;
                            chukudan=rowData;
                            chukuleixing = rowData.chukuleixing
                            $('#sp').empty();//清空sp内容
                        }, onHidePanel: function () {
                            record = product;
                            $('#sp').empty();
                            var table = "<table><thead><tr><td></td>";
                            for (var i = 0; i < record.sizeArray.length; i++) {
                                table += "<td align='center'><span class='cm'>" + record.sizeArray[i] + "</span></td>"
                            }
                            table += "<td align='center'>小计</td></tr></tr></thead><tbody>"
                            for (var i = 0; i < record.colorArray.length; i++) {
                                table += "<tr><td>" + record.colorArray[i] + "</td>"
                                for (var j = 0; j < record.sizeArray.length; j++) {
                                    table += "<td><input name='shuliang' class='easyui-validatebox cs' validType='INT'  style='width:50px; border-radius:5px'"   //
                                    for (var zz = 0; zz < chukudan.chukuson.length; zz++) {
                                        if (chukudan.chukuson[zz].color == record.colorArray[i] && chukudan.chukuson[zz].size == record.sizeArray[j]) {
                                            table += " placeholder=" + chukudan.chukuson[zz].shuliang + "";
                                            break;
                                        }
                                    }
                                    table += " placeholder=0></td>"
                                }
                                table += "<td><input name='shuliang'   class='easyui-validatebox ' validType='YZ' style='width:50px;border-radius:5px'></td>" //
                                table += "</tr>"
                            }
                            table += "</tbody></table><span></span>";
                            $('#sp').append(table)
                            $('#cc').combo('showPanel');
                            $.parser.parse($("#sp"));//格式样式
                            $("#sp .cs").keyup(function () {
                                var sum = 0;
                                for (var j = 1; j < $("#sp table td").length / $("#sp table tr").length - 1; j++) {
                                    if (/^[+]?[0-9]+\d*$/.test(parseInt($("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq(j).children().val()))) {
                                        sum += parseInt($("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq(j).children().val())
                                    }
                                }
                                $("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq($("#sp table td").length / $("#sp table tr").length - 1).children().val(sum)
                            });
                            flg = false
                            $("#sp table").find("tr").eq(1).find("td").eq(1).children().focus()


                        }
                    })

                }, loadFilter: function (data) {
                    return data.data
                },onLoadSuccess:function(){
                    $('#se').next('span').find('input').focus();
                }
            })
        }
    });
    $('#chukuId').val("")
    $('#h2').text("销 售 退 货 单")
    $('#w').window('open')
}

function winClose() {
    $('#bjdg').datagrid('loadData', {
        total: 0,
        rows: []
    });// 重置dataGRID
    $('#zk1').attr('checked', 'checked');
    $("#zongjia").text(0.00);
    $("#zongjianshu").text(0)
    $("#zongkuanshu").text(0)
    $("#SHDZ").val('')
    $('#phone').val('')
    $('#chukuId').val("")
    $('#w').window('close')

}

$(function () {

    $('#bjdg').datagrid(
        {
            iconCls: 'icon-edit',
            singleSelect: false,
            title: '编辑商品',
            fitColumns: true,
            onDblClickRow: onClickRow,

            columns: [[
                {
                    field: 'id',
                    title: 'productID',
                     checkbox: true,
                    align: 'center'
                }, {
                    field: 'product',
                    title: '款号',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'productName',
                    title: '款名',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'color',
                    title: '颜色',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'size',
                    title: '尺码',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'pinpai',
                    title: '品牌',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'year',
                    title: '年份',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'season',
                    title: '季节',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'price',
                    title: '铭牌价',
                    width: 90,
                    align: 'right',
                    formatter:function(value, row, index){
                        if(value!=null && value!=''){
                            return value.toFixed(2)
                        }
                        return value

                    }
                }, {
                    field: 'zhekou',
                    title: '折扣',
                    width: 90,
                    align: 'right',
                    editor: {
                        type: 'validatebox',
                        options: {
                            required: true,
                            validType: 'RANGE[0,1]'

                        }
                    }
                }, {
                    field: 'sjdanjia',
                    title: '实际单价',
                    width: 90,
                    align: 'right',
                    editor: {
                        type: 'validatebox',
                        options: {
                            required: true,
                            validType: 'FL'

                        }
                    }
                }, {
                    field: 'shuliang',
                    title: '数量',
                    width: 90,
                    align: 'right',
                    editor: {
                        type: 'validatebox',
                        options: {
                            required: true,
                            validType: 'INTE'
                        }
                    }
                }, {
                    field: 'yanzheng',
                    title: '验证',
                    width: 90,
                    align: 'right',
                    hidden:true

                }, {
                    field: 'danjuId',
                    title: '出库Id',
                    width: 90,
                    align: 'right',
                    hidden:true

                }, {
                    field: 'sjzongjia',
                    title: '实际总价',
                    width: 90,
                    align: 'right'
                }

            ]]

        })

    /*出库上面表格*/
    $("#dg").datagrid({
        method: 'GET',
        striped: true,
        rownumbers: false,
        singleSelect: true,
        toolbar: '#tb',
        checkbox: false,
        fit: true,
        striped: true,
        fitColumns: false,
        autoRowHeight: false,
        rownumbers: true,
        pagination: true,
        pageSize: 15,
        pageList: [15, 30, 50],
        nowrap: true,
        loadMsg: '加载中,请稍后......',
        columns: [[{
            field: 'id',
            title: '出库单Id',
            width: 80,
            hidden: true
        },{
            field: 'jgName',
            title: '所属机构',
            width: 130,
            align: 'center'
        }, {
            field: 'chukudanhao',
            title: '出库单号',
            width: 130,
            align: 'center'
        }, {
            field: 'state',
            title: '状态',
            width: 90,
            align: 'center',
            styler: function (value, row, index) {

                if (row.state == 0) {

                    return 'color:red;'
                } else if (row.state == 1) {

                    return 'color:yellow'

                }else if (row.state == 2) {
                    return 'color:orange'
                } else {
                    return 'color:green'
                }
            },
            formatter: function (value, row, index) {
                if (value == 0) {
                    if (row.bohuishijian != null) {
                        return '草稿(驳回)'
                    } else {
                        return '草稿'
                    }
                } else if (value == 1) {
                    return '待审核'
                } else if (value == 2) {
                    return '已审核'
                } else if (value == 3) {
                    return '已入库'
                }
            }
        },  {
            field: 'chukuleixing',
            title: '退货类型',
            width: 80,
            align: 'center',
            formatter: function (value, row, index) {
                if (row.fenlei == 1) {
                        return "销售退货";
                } else if (row.fenlei == 2) {
                        return "次品退货"
                }
            }
        }, {
            field: 'wldwName',
            title: '客户名称',
            width: 130,
            align: 'center'
        }, {
            field: 'phone',
            title: '联系方式(客户)',
            width: 90,
            align: 'center'
        }, {
            field: 'zshuliang',
            title: '总件数',
            width: 90,
            align: 'right',
            formatter: function (value, row, index) {
                if (value < 0) {
                    value = value * -1
                }
                return value
            }
        }, {
            field: 'zongjia',
            title: '总金额',
            width: 90,
            align: 'right',
            formatter: function (value, row, index) {
                if (value < 0) {
                    value = value * -1
                }
                return value.toFixed(2)
            }
        }, {
            field: 'zhidanshijian',
            title: '制单时间',
            width: 150,
            align: 'center'
        }, {
            field: 'zhidanrenName',
            title: '制单人',
            width: 80,
            align: 'center'
        }, {
            field: 'shenheshijian',
            title: '提交时间',
            width: 150,
            align: 'center'
        }, {
            field: 'shenherenName',
            title: '提交人',
            width: 80,
            align: 'center'
        }, {
            field: 'tongguoshijian',
            title: '审核时间',
            width: 150,
            align: 'center'
        }, {
            field: 'tongguorenName',
            title: '审核人',
            width: 80,
            align: 'center'
        }
            , {
                field: 'chukushijian',
                title: '入库时间',
                width: 150,
                align: 'center'
            }, {
                field: 'chukurenName',
                title: '入库人',
                width: 90,
                align: 'center'
            }, {
                field: 'bohuishijian',
                title: '驳回时间',
                width: 150,
                align: 'center'
            }, {
                field: 'bohuirenName',
                title: '驳回人',
                width: 80,
                align: 'center'
            }, {
                field: 'beizhu',
                title: '驳回备注',
                width: 120,
                align: 'center'
            }, {
                field: 'note',
                title: '审核备注',
                width: 120,
                align: 'center'
            }
        ]],
        onSelect: function (index, row) {
            loadChildren($(".fenlei:checked").val())
        },
        onBeforeLoad: function (param) {
        },
        onLoadSuccess: function (data) {

            $('#dg').datagrid("selectRow", 0);
            $('#key').next('span').find('input').focus()

        }
    });

    $('#subDatagrid').datagrid({
        striped: true,
        rownumbers: false,
        singleSelect: true,
        toolbar: '#tb3',
        checkbox: false,
        fit: true,
        striped: true,
        fitColumns: false,
        autoRowHeight: false,
        rownumbers: true,
        nowrap: true,
        loadMsg: '加载中,请稍后......',
        columns: [[{
            field: 'productrRetailId',
            title: '商品编号',
            width: 80,
            hidden: true
        },{
            field: 'productId',
            title: '商品款号',
            width: 80,
            hidden: true
        },{
            field: 'product',
            title: '商品款号',
            width: 80,  align: 'center'

        },{
            field: 'productName',
            title: '商品名称',
            width: 80,align: 'center'

        },{
            field: 'price',
            title: '铭牌价',
            width: 80,align: 'right'
        },{
            field: 'color',
            title: '颜色',
            width: 80,align: 'center'

        },{
            field: 'size',
            title: '尺码',
            width: 80,align: 'center'
        },{
            field: 'zongshu',
            title: '数量',
            width: 80,align: 'right'
        },{
            field: 'danjia',
            title: '单价',
            width: 80,align: 'right',
            formatter:function(value, row, index){
                if(value!=null){
                    return value.toFixed(2)
                }
                return value

            }
        },{
            field: 'zongjia',
            title: '总价',
            width: 80,align: 'right',
            formatter:function(value, row, index){
                if(value!=null){
                    return value.toFixed(2)
                }
                return value

            }
        },{
            field: 'chukudanhao',
            title: '原单据',
            width: 140,align: 'center'
        },{
            field: 'nikeName',
            title: '销售人',
            width: 80,align: 'center'
        },{
            field: 'jgName',
            title: '原发货方',
            width: 80,align: 'center'
        }

        ]],
        loadFilter: function (data) {
            return data.data
        }, onLoadSuccess:function(){
            if($(".fenlei:checked").val()==0){
                $('#subDatagrid').datagrid("hideColumn","color")
                $('#subDatagrid').datagrid("hideColumn","size")
            }else if($(".fenlei:checked").val()==1){
                $('#subDatagrid').datagrid("showColumn",'color')
                $('#subDatagrid').datagrid("hideColumn",'size')

            }else if($(".fenlei:checked").val()==2){
                $('#subDatagrid').datagrid("showColumn",'color')
                $('#subDatagrid').datagrid("showColumn",'size')

            }

        }
    })


})


var editIndex = undefined;
function endEditing() {
    if (editIndex == undefined) {
        return true
    }
    if ($('#bjdg').datagrid('validateRow', editIndex)) {
        $('#bjdg').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

function onClickRow(index) {
    if (editIndex != index) {
        if (endEditing()) {
            $('#bjdg').datagrid('clearSelections');
            $('#bjdg').datagrid('selectRow', index)
                .datagrid('beginEdit', index);
            setEditing(index);
            editIndex = index;
        } else {
            $('#bjdg').datagrid('selectRow', editIndex);
        }

    }
    sum()
}


//保存编辑
function accept() {

    if (endEditing()) {
        if(shu()) {//shu()
            for (var i = 1; i < $("#sp table tr").length; i++) {
                for (var j = 1; j < $("#sp table td").length / $("#sp table tr").length - 1; j++) {
                    if ($("#sp table").find("tr").eq(i).find("td").eq(j).children().val() == '' || $("#sp table").find("tr").eq(i).find("td").eq(j).children().val() == 0) {
                        continue
                    }
                    $('#bjdg').datagrid('appendRow', {
                        id: product.id,
                        product: product.product,
                        productName: product.productName,
                        color: $("#sp table").find("tr").eq(i).find("td").eq(0).text(),
                        size: $("#sp table").find("tr").eq(0).find("td").eq(j).children('.cm').text(),
                        pinpai: product.pinpai,
                        year: product.year,
                        season: product.season,
                        price: product.price,
                        zhekou: (chukudan.danjia / product.price).toFixed(2),
                        sjdanjia: chukudan.danjia,
                        danjuId: chukudan.id,
                        yanzheng: $("#sp table").find("tr").eq(i).find("td").eq(j).children().attr('placeholder'),
                        shuliang: $("#sp table").find("tr").eq(i).find("td").eq(j).children().val(),
                        sjzongjia: (chukudan.danjia * $("#sp table").find("tr").eq(i).find("td").eq(j).children().val()).toFixed(2)

                    });
                }
            }
            sum()
            $('#sp').empty();
            $('#se').combobox("clear")
            $('#cc').combo('hidePanel');
            $('#se').combobox().next('span').find('input').focus()// 聚焦到combobox
            flag = false
        }
    }
}

//求总数量和总价
function sum() {
    var rows = $("#bjdg").datagrid("getRows");
    var zongjia = 0;
    var zongjianshu = 0;
    var productId = []
    for (var i = 0; i < rows.length; i++) {
        zongjianshu += parseInt(rows[i].shuliang);
        zongjia += parseFloat(rows[i].sjzongjia)
        productId.push(rows[i].id)
    }
    $("#zongjia").text(zongjia.toFixed(2));
    $("#zongjianshu").text(zongjianshu)
    $("#zongkuanshu").text(uniq(productId).length)

}


//
function setEditing(rowIndex) {
    var editors = $('#bjdg').datagrid('getEditors', rowIndex);

    var zhekou = editors[0];
    var danjia = editors[1];
    var shuliang = editors[2];

    zhekou.target.bind('change', function () {
        calculate1();
    });
    danjia.target.bind('change', function () {
        calculate2();
    });
    shuliang.target.bind('change', function () {
        calculate3();
    });

    //改zhekou
    function calculate1() {
        var rows = $('#bjdg').datagrid('getRows')
        if ($('#zk1').prop('checked')) {
            if ($('#bjdg').datagrid('validateRow', editIndex)) {
                $(danjia.target).val(parseFloat($('#bjdg').datagrid('getRows')[editIndex]['price'] * zhekou.target.val()).toFixed(2));
                $('#bjdg').datagrid('getRows')[editIndex]['sjzongjia'] = parseFloat(danjia.target.val() * shuliang.target.val()).toFixed(2)

                for (var i = 0; i < rows.length; i++) {
                    rows[i]['zhekou'] = zhekou.target.val()
                    rows[i]['sjdanjia'] = (zhekou.target.val() * rows[i]['price']).toFixed(2)
                    rows[i]['sjzongjia'] = (rows[i]['sjdanjia'] * rows[i]['shuliang']).toFixed(2)
                    $('#bjdg').datagrid('refreshRow', i)
                }
            }

        } else if ($('#zk2').prop('checked')) {
            if ($('#bjdg').datagrid('validateRow', editIndex)) {
                $(danjia.target).val(parseFloat($('#bjdg').datagrid('getRows')[editIndex]['price'] * zhekou.target.val()).toFixed(2));
                $('#bjdg').datagrid('getRows')[editIndex]['sjzongjia'] = parseFloat(danjia.target.val() * shuliang.target.val()).toFixed(2)

                for (var i = 0; i < rows.length; i++) {
                    if (rows[i]['id'] == $('#bjdg').datagrid('getRows')[editIndex]['id']) {
                        rows[i]['zhekou'] = zhekou.target.val()
                        rows[i]['sjdanjia'] = (zhekou.target.val() * rows[i]['price']).toFixed(2)
                        rows[i]['sjzongjia'] = (rows[i]['sjdanjia'] * rows[i]['shuliang']).toFixed(2)
                        $('#bjdg').datagrid('refreshRow', i)
                    }
                }
            }
        }

        endEditing()
        sum()
    }

    //改单价
    function calculate2() {
        var rows = $('#bjdg').datagrid('getRows')
        if ($('#bjdg').datagrid('validateRow', editIndex)) {
            $(zhekou.target).val(parseFloat(danjia.target.val() / $('#bjdg').datagrid('getRows')[editIndex]['price']).toFixed(2));
            $('#bjdg').datagrid('getRows')[editIndex]['sjzongjia'] = parseFloat(danjia.target.val() * shuliang.target.val()).toFixed(2)
        }
        for (var i = 0; i < rows.length; i++) {
            if (rows[i]['id'] == $('#bjdg').datagrid('getRows')[editIndex]['id']) {
                rows[i]['sjdanjia'] = danjia.target.val()
                rows[i]['zhekou'] = (danjia.target.val() / rows[i]['price']).toFixed(2)
                rows[i]['sjzongjia'] = (rows[i]['sjdanjia'] * rows[i]['shuliang']).toFixed(2)
                $('#bjdg').datagrid('refreshRow', i)
            }
        }
        endEditing()
        sum()
    }

    //改数量
    function calculate3() {

        if ($('#bjdg').datagrid('validateRow', editIndex)) {
            $('#bjdg').datagrid('getRows')[editIndex]['sjzongjia'] = parseFloat(danjia.target.val() * shuliang.target.val()).toFixed(2)
        }
        endEditing()
        sum()
    }
}

// 验证输入数量
function shu() {
    for (var i = 1; i < $("#sp table tr").length; i++) {
        for (var j = 1; j < $("#sp table td").length / $("#sp table tr").length - 1; j++) {
            if ($("#sp table").find("tr").eq(i).find("td").eq(j).children().val() != '' && $("#sp table").find("tr").eq(i).find("td").eq(j).children().val() != 0) {
                if (!/^[+]?[1-9]+\d*$/.test($("#sp table").find("tr").eq(i).find("td").eq(j).children().val())) {
                    $('#cc').combo('showPanel')
                    $("#sp table").find("tr").eq(i).find("td").eq(j).children().focus()
                    return false;
                }
                   if (parseInt($("#sp table").find("tr").eq(i).find("td").eq(j).children().attr('placeholder')) < $("#sp table").find("tr").eq(i).find("td").eq(j).children().val()) {
                       $('#cc').combo('showPanel')
                       $("#sp table").find("tr").eq(i).find("td").eq(j).children().focus()
                            return false;
                        }
                   }
                }
        }

    if($("#sp table td").length==0){

        return false
    }
    if($('#bjdg').datagrid('getRows').length!=0){
        for(var i=0;i<$('#bjdg').datagrid('getRows').length;i++){

            if($('#se').combobox('getText')==$('#bjdg').datagrid('getData').rows[i].product )// 亚麻色
            {
                for (var j = 1; j < $("#sp table tr").length; j++) {

                    if($("#sp table").find("tr").eq(j).find("td").eq(0).text()!=''){

                        for (var z = 1; z < $("#sp table td").length/$("#sp table tr").length-1; z++) {

                            if($("#sp table").find("tr").eq(j).find("td").eq(z).children().val()!=''){
                                if($("#sp table").find("tr").eq(j).find("td").eq(0).text()==$('#bjdg').datagrid('getData').rows[i].color){

                                    if($("#sp table").find("tr").eq(0).find("td").eq(z).children('.cm').text()==$('#bjdg').datagrid('getData').rows[i].size){
                                        $('#cc').combo('hidePanel');
                                        doSearch($('#se').combobox('getText'))
                                        alert($('#se').combobox('getText')+":"+$("#sp table").find("tr").eq(j).find("td").eq(0).text()+":"+$("#sp table").find("tr").eq(0).find("td").eq(z).children('.cm').text()+'已添加')
                                        return 	false;

                                    }

                                }


                            }

                        }


                    }
                }
            }
        }
    }
    return true;
}


// 添加出库
function addChuKu() {

    var chukuson = "["

    var rows = $("#bjdg").datagrid("getRows");

    if (rows == '') {
        $.messager.alert('提示!', '无编辑数据!', 'warning');
        return
    }
    if ($("#yearandseason").combobox("getText") == '') {
        $.messager.alert('提示!', '年季不能为空!', 'warning');
        return

    }
    var chukuId = [];
    for (var i = 0; i < rows.length; i++) {

        chukuson += "{'productoinId':'" + rows[i].id + "','color':'" + rows[i].color + "','size':'" + rows[i].size + "','shuliang':'" + rows[i].shuliang + "','danjia':'" + rows[i].sjdanjia + "'},"
        chukuId.push(rows[i].danjuId)
    }

    chukuson = chukuson.substring(0, chukuson.length - 1) + "]"
    $('#save1').linkbutton('disable');
    $('#noqiuxiao').linkbutton('disable');
    $.ajax({
        url:  path+'/chuku/save.do',
        type: 'post',
        traditional: true,
        data: {
            id: $('#chukuId').val(),
            wanglaidanwei: $("#kehu").val(),
            phone: $('#phone').val(),
            address: "",
            chukusonString: chukuson,
            chukuleixing: chukuleixing,
            fenlei: $('#thno').val(),
            yearandseason: $('#yearandseason').combobox("getText"),
            chukuIdArray: uniq(chukuId)

        },
        dataType: 'json',
        success: function (data) {

            if (data.code == 200) {
                winClose()
                getChuKuList()
                $.messager.show({
                    title: '提示',
                    msg: data.msg,
                    timeout: 4000,
                    showType: 'slide'
                })
            } else {
                alert(data.msg)
            }
        }, complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
            if (status == 'timeout') {// 超时,status还有success,error等值的情况
                ajaxTimeoutTest.abort();
                $.messager.show({
                    title: '提示',
                    msg: '请求超时！',
                    timeout: 1000,
                    showType: 'slide'
                });
                $('#save1').linkbutton('enable');
                $('#noqiuxiao').linkbutton('enable');
            }
            $('#save1').linkbutton('enable');
            $('#noqiuxiao').linkbutton('enable');
        }

    })
    $('#chukuId').val('')
}


// 编辑删除
function removeit() {
    var selRow = $('#bjdg').datagrid('getSelections')
    if (selRow == 0) {
        alert('请选择要删除的行！');
        return

    } else {
        $.messager.confirm('提示信息', '真的要执行删除操作', function (r) {
            if (r) {
                for (var i = 0; i < selRow.length; i++) {
                    var index = $('#bjdg').datagrid(
                        'getRowIndex', selRow[i]);
                    $('#bjdg').datagrid('cancelEdit', editIndex)
                        .datagrid('deleteRow', index);
                    sum();
                    editIndex = undefined;
                }
            }
        })
    }
}


//添加回执单图片
function huiPic() {

    /*    alert("添加图片")*/
    $('#wpicture').window('open')
}

//出库单提交
function commit() {

    if ($('#bumeng').combotree('getValue') != $("#jgid").val()) {
        alert("不可以操作非本机构数据！");
        return;
    }
    if ($('#dg').datagrid("getSelected") != null) {
        $.messager.confirm('提示信息', '请确认提交：' + $('#dg').datagrid("getSelected").chukudanhao, function (r) {
            if (r) {
                $('#tj').linkbutton('disable');
                $.ajax({
                    url: path + '/chuku/updatechuku.do',
                    type: 'post',
                    data: {
                        chukuId: $('#dg').datagrid("getSelected").id,
                        state: 1,
                        beizhu: ''
                    },
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 200) {
                            getChuKuList()
                            $.messager.show({
                                title: '提示',
                                msg: '提交成功！',
                                timeout: 400,
                                showType: 'slide'
                            });
                            getChuKuList()
                        } else {
                            alert(data.msg)
                            $('#tj').linkbutton('enable');
                        }
                    }, complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
                        if (status == 'timeout') {// 超时,status还有success,error等值的情况
                            ajaxTimeoutTest.abort();
                            $.messager.show({
                                title: '提示',
                                msg: '请求超时！',
                                timeout: 1000,
                                showType: 'slide'
                            });
                            $('#tj').linkbutton('enable');

                        }
                        $('#tj').linkbutton('enable');

                    }
                })
            }
        });
    } else {
        alert("请选择操作行!")
    }

}

//审核通过还是驳回

function shenhe(state) {
    if ($('#bumeng').combotree('getValue') != $("#jgid").val()) {
        alert("不可以操作非本机构数据！");
        return;
    }

    if ($('#dg').datagrid("getSelected") != null) {
        $.messager.prompt('提示信息', '下框添加备注，可为空', function (r) {
            if(r==""){
                r=" "
            }
            if (r) {
                if (state == 0) {
                    $('#bh').linkbutton('disable');
                } else if (state == 2) {
                    $('#tg').linkbutton('disable');
                }
                $.ajax({
                    url: path + '/chuku/updatechuku.do',
                    type: 'post',
                    data: {
                        chukuId: $('#dg').datagrid("getSelected").id,
                        state: state,
                        beizhu: r
                    },
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 200) {
                            getChuKuList()
                            $.messager.show({
                                title: '提示',
                                msg: '提交成功！',
                                timeout: 400,
                                showType: 'slide'
                            });

                        } else {
                            alert(data.msg)
                            if (state == 0) {
                                $('#bh').linkbutton('enable');
                            } else if (state == 2) {
                                $('#tg').linkbutton('enable');
                            }
                        }
                    }, complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
                        if (status == 'timeout') {// 超时,status还有success,error等值的情况
                            ajaxTimeoutTest.abort();
                            $.messager.show({
                                title: '提示',
                                msg: '请求超时！',
                                timeout: 1000,
                                showType: 'slide'
                            });

                            if (state == 0) {
                                $('#bh').linkbutton('enable');
                            } else if (state == 2) {
                                $('#tg').linkbutton('enable');
                            }
                        }
                        if (state == 0) {
                            $('#bh').linkbutton('enable');
                        } else if (state == 2) {
                            $('#tg').linkbutton('enable');
                        }

                    }
                })
            }
        });
    } else {
        alert("请选择操作行!")
    }

}


//删除单

function del() {
    if ($('#bumeng').combotree('getValue') != $("#jgid").val()) {
        alert("不可以操作非本机构数据！");
        return;
    }
    if ($('#dg').datagrid("getSelected") != null) {
        $.messager.confirm('提示信息', '请确认删除：' + $('#dg').datagrid("getSelected").chukudanhao, function (r) {
            if (r) {
                $('#sc').linkbutton('disable');
                $.ajax({
                    url: path + '/chuku/delchuku.do',
                    type: 'post',
                    data: {
                        chukuId: $('#dg').datagrid("getSelected").id
                    },
                    success: function (data) {
                        if (data.code == 200) {
                            console.log(data.msg)
                            getChuKuList()
                            $.messager.show({
                                title: '提示',
                                msg: data.msg,
                                timeout: 400,
                                showType: 'slide'
                            });
                            $('#sc').linkbutton('enable');
                        } else {

                            alert(data.msg)

                        }
                    }, complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
                        if (status == 'timeout') {// 超时,status还有success,error等值的情况
                            ajaxTimeoutTest.abort();
                            $.messager.show({
                                title: '提示',
                                msg: '请求超时！',
                                timeout: 1000,
                                showType: 'slide'
                            });
                            $('#sc').linkbutton('enable');

                        }
                        $('#sc').linkbutton('enable');

                    }

                })

            }
        })
    }else{
        alert("请选择操作行!")
    }
}

/***
 * 修改
 */
function xiugai() {
    if ($('#bumeng').combotree('getValue') != $("#jgid").val()) {
        alert("不可以操作非本机构数据！");
        return;
    }
  if($('#dg').datagrid("getSelected")!=null){
      $.ajax({
          url: path + '/chuku/xiuchuku.do',
          type: "post",
          data: {
              chukuId: $('#dg').datagrid("getSelected").id
          },
          dataType: 'json',
          success: function (data) {
              if (data.code == 200) {
                  //开始
                  $("#chukudan").combogrid({
                      panelWidth: 550,
                      width: 150,
                      fitColumns: true,
                      height: 25,
                      idField: 'id',
                      textField: 'chukudanhao',
                      mode: 'remote',
                      url: path + '/chuku/chukudan.do',
                      columns: [[
                          {field: 'id', title: '入库Id', hidden: 'true'},
                          {field: 'chukudanhao', title: '出库单号', align: 'center'},
                          {
                              field: 'chukuleixing', title: '出库类型', align: 'center',
                              formatter: function (value, row, index) {
                                  if (value == 0) {
                                      return "批发"
                                  } else if (value == 1) {
                                      return "分销"
                                  } else {
                                      return "其他"
                                  }
                              }
                          },
                          {
                              field: 'state', title: '状态', align: 'center',
                              formatter: function (value, row, index) {
                                  if (value == 3) {
                                      return "已出库"
                                  } else {
                                      return "其他"
                                  }
                              }
                          },
                          {field: 'wldwName', title: '往来单位', align: 'center'},
                          {field: 'zshuliang', title: '总数量', align: 'right'},
                          {field: 'zongjia', title: '总价', align: 'right'},
                          {field: 'chukushijian', title: '出库时间', align: 'center'}
                      ]],
                      loadFilter: function (data) {
                          return data.data
                      },onLoadSuccess:function(){
                          $('#chukudan').combogrid('setValue',data.data[0].chukuson[0].danjuId)
                          $('#thno').val(data.data[0].fenlei)
                          var g = $('#chukudan').combogrid('grid');	// get datagrid object
                          var rowData = g.datagrid('getSelected');
                          $('#pifakehu').val(rowData.wldwName)
                          $('#kehu').val(rowData.wanglaidanwei)
                          $('#phone').val(rowData.phone)
                          $('#chukushijian').val(rowData.chukushijian)
                          danjuId = rowData.id;
                          chukuleixing = rowData.chukuleixing
                          $('#chukuId').val($('#dg').datagrid("getSelected").id)
                          $("#bjdg").datagrid("loadData", data.data[0].chukuson)
                          sum()
                          //结束
                          $("#se").combobox({
                              url: path + '/production/findAllProForChuKuId.do?chukuId=' + rowData.id,
                              valueField: 'id',
                              textField: 'product',
                              onSelect: function (record) {
                                  product = record
                                  $('#sp').empty();
                                  var table = "<table><thead><tr><td></td>";
                                  for (var i = 0; i < record.sizeArray.length; i++) {
                                      table += "<td align='center'><span class='cm'>" + record.sizeArray[i] + "</span></td>"
                                  }
                                  table += "<td align='center'>小计</td></tr></tr></thead><tbody>"
                                  for (var i = 0; i < record.colorArray.length; i++) {
                                      table += "<tr><td>" + record.colorArray[i] + "</td>"
                                      for (var j = 0; j < record.sizeArray.length; j++) {
                                          table += "<td><input name='shuliang' class='easyui-validatebox cs'  validType='INT' style='width:50px; border-radius:5px'"
                                          for (var zz = 0; zz < record.productionDetails.length; zz++) {
                                              if (record.productionDetails[zz].color == record.colorArray[i] && record.productionDetails[zz].size == record.sizeArray[j]) {
                                                  table += " placeholder=" + record.productionDetails[zz].shuliang + "";
                                                  break;
                                              }
                                          }

                                          table += " placeholder=0></td>"
                                      }
                                      table += "<td><input name='shuliang'   class='easyui-validatebox '  validType='YZ' style='width:50px;border-radius:5px'></td>"
                                      table += "</tr>"
                                  }

                                  table += "</tbody></table><span>快捷键操作</span>";
                                  $('#sp').append(table)
                                  $('#cc').combo('showPanel');
                                  $.parser.parse($("#sp"));//格式样式
                                  $("#sp .cs").keyup(function () {
                                      var sum = 0;
                                      for (var j = 1; j < $("#sp table td").length / $("#sp table tr").length - 1; j++) {
                                          if (/^[+]?[0-9]+\d*$/.test(parseInt($("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq(j).children().val()))) {
                                              sum += parseInt($("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq(j).children().val())
                                          }
                                      }
                                      $("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq($("#sp table td").length / $("#sp table tr").length - 1).children().val(sum)
                                  });

                              }, loadFilter: function (data) {

                                  return data.data
                              }, onHidePanel: function () {
                                  $("#sp table").find("tr").eq(1).find("td").eq(1).children().focus();

                              }
                          })

                          //

                      },
                      onSelect: function (rowIndex, rowData) {

                          $('#pifakehu').val(rowData.wldwName)
                          $('#kehu').val(rowData.wanglaidanwei)
                          $('#phone').val(rowData.phone)
                          $('#chukushijian').val(rowData.chukushijian)
                          danjuId = rowData.id;
                          chukuleixing = rowData.chukuleixing
                          $("#se").combobox({
                              url: path + '/production/findAllProForChuKuId.do?chukuId=' + rowData.id,
                              valueField: 'id',
                              textField: 'product',
                              onSelect: function (record) {
                                  product = record
                                  $('#sp').empty();
                                  var table = "<table><thead><tr><td></td>";
                                  for (var i = 0; i < record.sizeArray.length; i++) {
                                      table += "<td align='center'><span class='cm'>" + record.sizeArray[i] + "</span></td>"
                                  }
                                  table += "<td align='center'>小计</td></tr></tr></thead><tbody>"
                                  for (var i = 0; i < record.colorArray.length; i++) {
                                      table += "<tr><td>" + record.colorArray[i] + "</td>"
                                      for (var j = 0; j < record.sizeArray.length; j++) {
                                          table += "<td><input name='shuliang' class='easyui-validatebox cs'  validType='INT' style='width:50px; border-radius:5px'"
                                          for (var zz = 0; zz < record.productionDetails.length; zz++) {
                                              if (record.productionDetails[zz].color == record.colorArray[i] && record.productionDetails[zz].size == record.sizeArray[j]) {
                                                  table += " placeholder=" + record.productionDetails[zz].shuliang + "";
                                                  break;
                                              }
                                          }

                                          table += " placeholder=0></td>"
                                      }
                                      table += "<td><input name='shuliang'   class='easyui-validatebox '  validType='YZ' style='width:50px;border-radius:5px'></td>"
                                      table += "</tr>"
                                  }

                                  table += "</tbody></table><span>快捷键操作</span>";
                                  $('#sp').append(table)
                                  $('#cc').combo('showPanel');
                                  $.parser.parse($("#sp"));//格式样式
                                  $("#sp .cs").keyup(function () {
                                      var sum = 0;
                                      for (var j = 1; j < $("#sp table td").length / $("#sp table tr").length - 1; j++) {
                                          if (/^[+]?[0-9]+\d*$/.test(parseInt($("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq(j).children().val()))) {
                                              sum += parseInt($("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq(j).children().val())
                                          }
                                      }
                                      $("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq($("#sp table td").length / $("#sp table tr").length - 1).children().val(sum)
                                  });

                              }, loadFilter: function (data) {

                                  return data.data
                              }, onHidePanel: function () {
                                  $("#sp table").find("tr").eq(1).find("td").eq(1).children().focus();

                              }
                          })

                      }, onHidePanel: function () {
                          $('#se').next('span').find('input').focus();

                      }
                  })
                  $('#h2').text("销 售 退 货 单 (修改)")
                  $('#w').window('open')

              } else {
                  alert(data.msg)
              }
          }
      })
  }else{
      alert("请选择操作行!")
  }

}


function chuku(){

    if($('#bumeng').combotree('getValue')!=$("#jgid").val()){
        alert("不可以操作非本机构数据！");
        return;
    }

    if($('#dg').datagrid("getSelected")!=null){

        $.messager.confirm('提示信息', '请确认出库：'+$('#dg').datagrid("getSelected").chukudanhao, function(r){
            if (r){
                $('#rukuspan').linkbutton('disable');
                $.ajax({
                    url:path+'/chuku/chukux.do',
                    type:"post",
                    data:{
                        chukuId:$('#dg').datagrid("getSelected").id
                    },
                    dataType:'json',
                    success:function(data){

                        if(data.code==200){
                            getChuKuList()
                            $.messager.show({
                                title:'提示',
                                msg:data.msg,
                                timeout:1000,
                                showType:'slide'
                            });
                            $('#rukuspan').linkbutton('enable');
                        }else{
                            $('#rukuspan').linkbutton('enable');
                            alert(data.msg)
                        }
                    },complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
                        if (status == 'timeout') {// 超时,status还有success,error等值的情况
                            ajaxTimeoutTest.abort();
                            $.messager.show({
                                title:'提示',
                                msg:'请求超时！',
                                timeout:1000,
                                showType:'slide'
                            });
                        }
                        $('#rukuspan').linkbutton('enable')

                    }
                })
            }
        })

    }

}


//数组去重
function uniq(array) {
    var temp = [];
    var index = [];
    var l = array.length;
    for (var i = 0; i < l; i++) {
        for (var j = i + 1; j < l; j++) {
            if (array[i] === array[j]) {
                i++;
                j = i;
            }
        }
        temp.push(array[i]);
        index.push(i);
    }

    return temp;
}

//次品退货
function cipin() {
$('#thno').val(2)
    winOpen()
}

function xinzen() {
    $('#thno').val(1)
    winOpen()
}


//打印
function print(){
    if ($('#bumeng').combotree('getValue') != $("#jgid").val()) {
        alert("不可以操作非本机构数据！");
        return;
    }

    if ($('#dg').datagrid("getSelected") != null) {
        $('#print').linkbutton('disable');
        var url= path + '/print.do?chukuId='+$('#dg').datagrid("getSelected").id
        window.open(url)
        $('#print').linkbutton('enable');
    }else{
        alert("请选择操作行!")
    }

}
